package com.saas.shopping.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * Created with IntelliJ IDEA.
 * User: ljc
 * Date: 2023/02/16 15:52
 * Description:
 * Version: V1.0
 *
 * @author: ljc
 */
@Configuration
public class ActiveMQConfig {
    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;
    @Value("${spring.activemq.user}")
    private String username;
    @Value("${spring.activemq.password}")
    private String password;
    @Value("${spring.activemq.queue-name}")
    private String queueName;
    @Value("${spring.activemq.topic-name}")
    private String topicName;
    @Bean(name = "queue")
    public Queue queue() {
        return new ActiveMQQueue(queueName);
    }
    @Bean(name = "topic")
    public Topic topic() {
        return new ActiveMQTopic(topicName);
    }
    @Bean
    public ConnectionFactory connectionFactory(){
        return new ActiveMQConnectionFactory(username, password,
                brokerUrl);
    }

    /**
     * 发送请求
     * @return
     */
    @Bean(name = "msgTemplate")
    public JmsMessagingTemplate jmsMessageTemplate(){
//        JmsTemplate jmsTemplate=new JmsTemplate(connectionFactory());
        JmsMessagingTemplate jmsMessagingTemplate=new JmsMessagingTemplate(connectionFactory());
//        //事务签收设置为手动模式
//        jmsTemplate.setSessionTransacted(false);
//        //改为ActiveMQ独有的单条消息手动签收方式
//        jmsTemplate.setSessionAcknowledgeMode(4);
        return jmsMessagingTemplate;
    }

    /**
     * 接收请求
     * @param connectionFactory
     * @return
     */
    @Bean
    public SimpleJmsListenerContainerFactory firstFactory(ConnectionFactory connectionFactory){
        //如果在监听器中为接收消息设置ack签收模式
        SimpleJmsListenerContainerFactory factory=new SimpleJmsListenerContainerFactory();
        //关闭事务
        factory.setSessionTransacted(false);
        //开启手动签收
        factory.setSessionAcknowledgeMode(4);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }
}
